package web;

import controller.Controller;
import controller.ControllerManager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;

/**
 *请求分发器：根据路径分发请求
 */
public class MyDispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.print("init:");
        System.out.println(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("");
//        获取所有消息头的名称
        Enumeration e = req.getHeaderNames();
        while (e.hasMoreElements()){
//            遍历Enumeration获取每一个消息头的名称
            String headerName = e.nextElement().toString();
//            输出消息头的名-值对儿信息
            System.out.println(headerName+":"+req.getHeader(headerName));
        }
        System.out.println("请求方式："+req.getMethod());
        System.out.println("请求的协议种类:"+req.getProtocol());
        System.out.println("请求资源路径:"+req.getRequestURI());
        System.out.println("请求路径信息:"+req.getRequestURL());
        System.out.println("请求的上下文:"+req.getContextPath());
        String path = req.getServletPath();
        System.out.println("请求的Servlet路径:"+path);
        System.out.println("");
        String[] logPaths = new String[]{"/toLogin.action","/login.action","/logout.action"};
        String[] verifyPaths = new String[]{"/verify.action"};
        Controller controller =null;
        if(Arrays.asList(logPaths).contains(path)){
            controller = ControllerManager.getLoginController();
        }else if (Arrays.asList(verifyPaths).contains(path)){
            controller = ControllerManager.getVerifyController();
        }else
            throw new ServletException();
        controller.doService(req,resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
